/**
 * 查看订单详情弹窗
 */
import { getOnceOrderDetail, managerCancel, onceOrderRefund, updateOnceOrderStatus } from '@/services/order/api';
import { OrderStatus } from '@/utils/constants';
import { isNull, showMsg, setPageSize } from '@/utils/utils';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Col, Descriptions, Divider, Modal, Popconfirm, Row } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
// @ts-ignore
import Auditing from '@/components/Auditing';
import PermissionControl from '@/components/PermissionControl';
import { print } from '@/utils/utils';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import QRCode from 'qrcode.react';
import { isMobile } from 'react-device-detect';
import ReactToPrint from 'react-to-print';
import { eyeInfoColumn, frameInfoColumn } from './EyeInfo';
import PrintBillHTML from './PrintBillHTML';

const { info } = Modal;
let timerId;

const OnceOrderDetail: React.FC<any> = (props) => {
  const {
    record = {},
    handleModalVisible,
    optCallback,
    isPrint
  } = props;
  const [loading, setLoading] = useState(false);
  // 验光数据的存储，眼科用到
  const [ygData, setYgData] = useState([]);
  // 是否弹出打印窗口
  const [printing, setPrinting] = useState(false);
  // 取消出院办结订单的状态
  const [showCancel, setShowCancel] = useState(false);
  //  一次性订单详情
  const [detail, setDetail] = useState<ORDERAPI.OnceOrderItem>({});
  // 付款码
  const [showQrCode, setShowQrCode] = useState(false);
  // 点击审批拒绝后显示的弹窗
  const [showRejectDialog, setShowRejectDialog] = useState<boolean>(false);
  const auditingRef = useRef();

  const { initialState } = useModel('@@initialState');

  const [billPrinting, setBillPrinting] = useState<boolean>(false);

  const [myRef, setMyRef] = useState(null);
  const columns: ProColumns<any>[] = [
    {
      title: '分类',
      dataIndex: 'class_name',
      hideInTable: printing,
    },
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: printing ? 100 : 150,
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      hideInTable: printing,
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      width: printing ? 120 : 150,
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      align: 'right',
    },
    {
      title: '原价',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      hideInTable: printing,
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      align: 'right',
    },
    {
      title: '折扣价',
      dataIndex: 'discount_price',
      valueType: 'money',
      align: 'right',
    },
    {
      title: '开单人',
      dataIndex: 'create_user_name',
      align: 'right',
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      align: 'right'
    }
  ]

  const columns2: ProColumns<any>[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id'
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name'
    },
    {
      title: '原折扣',
      dataIndex: 'discount',
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      align: 'right',
    },

    {
      title: '折扣价',
      dataIndex: 'discount_price',
      valueType: 'money',
      align: 'right',
    },
    {
      title: '退款数量',
      dataIndex: 'refund_num',
      align: 'right',
    },
    {
      title: '退款金额',
      dataIndex: 'refund_price',
      valueType: 'money',
      align: 'right',
    }
  ]

  const columns3 = [
    {
      title: '操作者',
      dataIndex: 'approve_user_name',
      render: (val, data) => data.approve_status === 'U' ? data.create_user_name : val,
    },
    {
      title: '工号',
      dataIndex: 'approve_user_id',
      render: (val, data) => data.approve_status === 'U' ? data.create_user_id : val,
    },
    {
      title: '操作时间',
      dataIndex: 'create_date',
      render: (val, data) => `${val} ${data.create_time}`
    },
    {
      title: '审批状态',
      dataIndex: 'approve_status',
      valueType: 'select',
      valueEnum: {
        Y: '通过',
        N: '拒绝',
        U: '待审批',
      }
    },
    {
      title: '拒绝原因',
      dataIndex: 'cause'
    }
  ]

  const columns_eye: ProColumns[] = [
    {
      title: '',
      dataIndex: 'c1',
      align: 'center',
      width: 110
    },
    {
      title: '球镜',
      dataIndex: 'c2',
      align: 'center',
      width: 100
    },
    {
      title: '柱镜',
      dataIndex: 'c3',
      align: 'center',
      width: 100
    },
    {
      title: '轴位',
      dataIndex: 'c4',
      align: 'center',
      width: 100
    },
    {
      title: '矫正前视力',
      dataIndex: 'c5',
      align: 'center',
      width: 100
    },
    {
      title: '矫正后视力',
      dataIndex: 'c6',
      align: 'center',
      width: 100
    },
    {
      title: '瞳距',
      dataIndex: 'c7',
      align: 'center',
      width: 100
    },
    {
      title: '总瞳距',
      dataIndex: 'c8',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    },
    {
      title: '瞳高',
      dataIndex: 'c9',
      align: 'center',
      width: 100
    },
    {
      title: '离焦量',
      dataIndex: 'c11',
      align: 'center',
      width: 100
    },
    {
      title: 'ADD',
      dataIndex: 'c12',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    }
  ];

  // 发起支付
  const startPay = async () => {
    try {
      setLoading(true);
      await updateOnceOrderStatus({
        order_id: record.order_id,
        order_status: 'W'
      });
      const data = await getOnceOrderDetail(record.order_id);
      // handleModalVisible(false);
      // optCallback && optCallback(data);
      // 提交支付
      const orderSumbitConfig = {
        title: '',
        content: `订单提交成功，请在【${data.pay_valid_time}】前完成缴费`
      };
      info(orderSumbitConfig);
      optCallback && optCallback(data);
      init();
    } catch (error) {
      setLoading(false);
      showMsg(error?.data?.errmsg);
    }
  }

  // 申请退款审批通过
  const agree = async () => {
    const data: any = {
      order_id: record.order_id,
      approve_status: 'Y'
    }
    setLoading(true);
    auditingRef?.current?.onSign({ sign_no: record.order_id, sign_string: JSON.stringify(data), title: '退款审批' }, async () => {
      onceOrderRefund(data).then(res => {
        setLoading(false);
        handleModalVisible(false);
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        optCallback && optCallback({
          order_status: record.order_status,
          type: 1
        });
      }).catch(error => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      });
    });
  }

  // 申请退款审批拒绝
  const reject = async (reason: string) => {
    const data: any = {
      order_id: record.order_id,
      approve_status: 'N',
      cause: reason
    }
    setLoading(true);
    auditingRef?.current?.onSign({ sign_no: record.order_id, sign_string: JSON.stringify(data), title: '退款审批' }, async () => {
      onceOrderRefund(data).then(res => {
        setLoading(false);
        handleModalVisible(false);
        optCallback?.({
          order_status: record.order_status,
          type: 2
        });
      }).catch(error => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      });
    })
  }

  useEffect(() => {
    init(isPrint);
  }, [record]);

  // 10s轮询一次支付结果
  const timer = () => {
    timerId = setInterval(() => init(false), 10000);
  }

  const init = (readyPrint?: boolean) => {
    if (record.order_id) {
      setLoading(true);
      getOnceOrderDetail(record.order_id).then((res) => {
        setLoading(false);
        setDetail(res);
        // 是否显示付款码
        setShowQrCode(res.order_status === 'W' && !isNull(res.pay_qr_code_url));
        const data = [{
          c1: '右眼（R）',
          c2: formatData(res.right_degrees),
          c3: formatData(res.right_astig),
          c4: res.right_axial,
          c5: res.right_rectify_bef,
          c6: res.right_rectify_af,
          c7: res.pup_distance_right,
          c8: res.pup_distance,
          c9: res.pup_high_right,
          c11: res.right_defocus,
          c12: res.madd
        }, {
          c1: '左眼（L）',
          c2: formatData(res.left_degrees),
          c3: formatData(res.left_astig),
          c4: res.left_axial,
          c5: res.left_rectify_bef,
          c6: res.left_rectify_af,
          c7: res.pup_distance_left,
          c8: res.pup_distance,
          c9: res.pup_high_left,
          c11: res.left_defocus,
          c12: res.madd
        }];
        if (!isNull(res.refund_service_price) && parseFloat(res.refund_service_price) > 0) {
          res.refund_order_goods_list.push({ id: '10086', goods_name: '配镜服务费', goods_total_price: res.refund_service_price });
        }
        setYgData(data);
        if (res.order_status === 'P') {
          // console.log('timer', timerId, res.order_status)
          clearInterval(timerId);
          timerId = null
        }
        // 待支付状态需要10s轮询
        if (res.order_status === 'W') {
          clearInterval(timerId)
          timerId = null;
          timer();
        }
        // 弹出打印窗口
        if (readyPrint) {
          // printPage();
          setTimeout(() => {
            document.getElementById('printBtn')?.click();
          }, 500);
        }
      }).catch(error => {
        setLoading(false);
        showMsg(error?.data?.errmsg);
      });
    }
  }

  // 判断是否需要显示随访数据
  const getSurveyIsShow = () => {
    if (!isNull(detail.survey_title) || !isNull(detail.survey_date)) {
      return true;
    }
    return false;
  }
  // 打印
  const printPage = () => {
    setPrinting(true);
    setTimeout(() => {
      print(document.querySelector('.order-modal .ant-modal-body'), {
        // printZoom: 0.9
        size: 'portrait'
      });
      setTimeout(() => {
        setPrinting(false);
      }, 5000);
    }, 500);
  }

  // console.log('ygdata', ygData)
  let no = 3;
  return <>
    <Modal
      title="查看订单"
      wrapClassName="order-modal"
      width="90%"
      bodyStyle={{ height: printing ? 'auto' : window.innerHeight - 185, overflowY: printing ? 'auto' : 'scroll' }}
      maskClosable={false}
      confirmLoading={loading}
      onCancel={() => { clearInterval(timerId); timerId = null; handleModalVisible(false) }}
      footer={[
        <Button key="back" onClick={() => {
          // console.log('关闭', timerId)
          clearInterval(timerId);
          timerId = null;
          handleModalVisible(false);
        }}>
          关闭
        </Button>,

        // 刷新支付状态
        ['W'].includes(detail.order_status as string) ?
          <Button loading={loading} key="pay" type="primary" onClick={() => { { clearInterval(timerId); timerId = null; init() } }}>
            刷新
          </Button> : null,
        // 开单状态、待支付状态可以进行取消
        ['C', 'W'].includes(detail.order_status as string) &&
        <PermissionControl action_id="400400004">
          {
            detail.manager_flag !== 'Y' ?
              <Popconfirm
                placement="topRight"
                key="cancel"
                title={detail.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : "您即将取消订单，是否继续？"}
                onConfirm={async () => {
                  if (detail.manager_flag === 'Y') {
                    await managerCancel(record.manager_order_id).then(res => {
                      showMsg('订单已取消', 'success');
                      optCallback?.({});
                      init();
                    }).catch(error => {
                      showMsg(error?.data?.errmsg)
                    });
                  } else {
                    await updateOnceOrderStatus({
                      order_id: detail.order_id,
                      order_status: 'E'
                    }).then(res => {
                      showMsg('订单已取消', 'success');
                      optCallback?.({});
                      init();
                    }).catch(error => {
                      showMsg(error?.data?.errmsg)
                    });
                  }
                }}
                okText="确认取消"
                cancelText="再想想">
                <Button style={{ margin: '0 10px' }}>取消</Button>
              </Popconfirm> :
              <Button style={{ marginLeft: 10 }} onClick={() => {
                setShowCancel(true);
              }}>取消</Button>
          }
        </PermissionControl>,

        // 开单状态且未办理出院办结可以发起支付
        (['C'].includes(detail.order_status as string) && detail.manager_flag === 'N') && !isMobile ?
          <PermissionControl action_id="400400007">
            <Button style={{ marginLeft: 10 }} loading={loading} key="pay" type="primary" onClick={() => { startPay() }}>
              发起支付
            </Button></PermissionControl> : null,

        // 眼视光科室待支付和已支付可以打印票据单
        (initialState?.currentUser?.dept_type === 'Y' && ['W', 'P', 'F'].includes(detail.order_status as string) && !isNull(detail.pay_qr_code_url)) ?
          <Button type='primary' key="printBill" onClick={() => setBillPrinting(true)}>打印票据单</Button> : null,

        // 待支付、已支付、已完成状态可以打印结算单
        (['W', 'P', 'F'].includes(detail.order_status as string) && !isNull(detail.pay_qr_code_url)) ?
          <PermissionControl action_id="400400008">
            {/* <Button style={{ marginLeft: 10 }} key="print" type="primary" onClick={printPage}>
              打印结算单
            </Button> */}
            <ReactToPrint
              trigger={() => <Button style={{ marginLeft: 10 }} key="print" id='printBtn' type="primary">
                打印结算单
              </Button>}
              content={() => myRef}
              bodyClass='ant-modal-body' // 把ant-modal-body的样式赋过来，这样样式才不会有问题
              onBeforeGetContent={() => {
                return new Promise((resolve) => {
                  setPrinting(true);
                  // setPageSize();
                  // 延迟执行，目的是为了让打印的样式先渲染
                  setTimeout(() => {
                    resolve(null);
                  }, 0);
                });
              }}
              onAfterPrint={() => {
                setPrinting(false);
              }}
            />
          </PermissionControl> : null,

        // 退款待审批
        ['A'].includes(detail.order_status as string) ?
          <PermissionControl action_id="400400009">
            <Auditing
              ref={auditingRef}
              loading={loading}
              module='O'
              onLoading={e => setLoading(e)}
              onError={() => {
                setLoading(false);
              }}
              onClick={() => {
                agree()
              }}
              _html={<Button loading={loading} style={{ marginLeft: 10 }} key="agree" type="primary">审批通过</Button>}
            />
          </PermissionControl> : null,

        ['A'].includes(detail.order_status as string) ?
          <PermissionControl action_id="400400009">
            <Auditing
              ref={auditingRef}
              loading={loading}
              module='O'
              onLoading={e => setLoading(e)}
              onError={() => {
                setLoading(false);
              }}
              onClick={() => {
                setShowRejectDialog(true)
              }}
              _html={<Button loading={loading} style={{ marginLeft: 10 }} key="reject" type="primary">审批拒绝</Button>}
            /></PermissionControl> : null
      ]}
      visible>

      {/* 打印的dom信息 */}
      {/* <div className="order-modal-content print_yes_width" style={{ width: printing ? '80%' : '100%', transform: printing ? 'scale(0.85)' : 'scale(1)', transformOrigin: '0 0' }} ref={ref => setMyRef(ref)}> */}
      <div className="order-modal-content print_yes_width" ref={ref => setMyRef(ref)}>
        {/* <div className="order-modal-content"> */}
        <div className='print_yes print_title'>缴费单</div>
        <Divider className='print_yes' style={{ paddingBottom: 15 }} />
        <div style={{ fontSize: 12, fontWeight: 'bold' }}>1.患者信息</div>
        <Divider />
        <div style={{ display: 'flex' }}>
          <Descriptions column={printing ? 1 : 6} style={{ flex: 1 }}>
            <Descriptions.Item span={1.5} label="身份证/住院号">{detail.identity_no}{!isNull(detail.identity_no) && !isNull(detail.admission_num) ? ` / ` : ''}{detail.admission_num}</Descriptions.Item>
            <Descriptions.Item style={{ width: 200 }} label="患者姓名">{detail.patient_name}</Descriptions.Item>
            {!isNull(detail.patient_sex_name) && <Descriptions.Item style={{ width: 150 }} label="患者性别">{detail.patient_sex_name || '-'}</Descriptions.Item>}
            <Descriptions.Item label="患者手机号">{detail.mobile || '-'}</Descriptions.Item>
            <Descriptions.Item label="归属科室">{detail.create_dept_name}</Descriptions.Item>
          </Descriptions>
          {
            (showQrCode && printing) &&
            <Descriptions style={{ flex: '0.5', float: 'right' }} className='print_ewm'>
              <Descriptions.Item label="扫码支付">
                <QRCode
                  // value参数为生成二维码的链接
                  value={detail.pay_qr_code_url || ''}
                  // 二维码的宽高尺寸
                  size={120}
                  // 二维码的颜色
                  fgColor="#000"
                  renderAs="svg"
                />
              </Descriptions.Item>
            </Descriptions>
          }
        </div>
        <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>2.商品信息</div>
        <Divider />
        <ProTable<STOCKGOODSAPI.GoodsItem>
          rowKey="record_id"
          style={{ marginTop: 14 }}
          options={false}
          search={false}
          columns={columns}
          pagination={false}
          dataSource={detail.order_goods_list}
          bordered />

        {
          isShowEyeInfo(detail) &&
          <>
            <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.配镜信息`}</div>
            <Divider />
            <ProTable
              rowKey="id"
              size='small'
              bordered
              // style={{ margin: '0 -24px' }}
              columns={columns_eye}
              // actionRef={actionRef1}
              search={false}
              options={false}
              dataSource={ygData}
              pagination={false}
            />
            <Descriptions column={4}>
              <Descriptions.Item span={1} label="用途">{museText[detail?.muse] || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="验光号">{detail.sight_no || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="就诊医生">{detail.doctor_name || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="验光师">{detail.optician_name || '-'}</Descriptions.Item>
              {
                !printing &&
                <Descriptions.Item span={3} label="特殊备注" labelStyle={{ color: 'red' }}>{detail.special_case || '-'}</Descriptions.Item>
              }
            </Descriptions>
          </>
        }

        {
          isShowFrameInfo(detail) &&
          <>
            <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.镜架信息`}</div>
            <Divider />
            <Descriptions column={4}>
              <Descriptions.Item span={1} label="框宽">{detail.frame_width || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="框高">{detail.frame_height || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="中梁">{detail.frame_middle || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="镜对角直径">{detail.frame_diagonal || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="型号">{detail.frame_model || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="框型">{detail.frame_material || '-'}</Descriptions.Item>
              <Descriptions.Item span={1} label="是否需要防滑套">{detail.is_slip === 'Y' ? '需要' : '不需要'}</Descriptions.Item>
              <Descriptions.Item span={1} label="是否自备镜架">
                {(detail.frame_flag ?? '0') == '0' ? '非自备' : (detail.frame_flag == '1' ? '自备/留' : '自备/未留')}
              </Descriptions.Item>
            </Descriptions>
          </>
        }

        <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.结算信息`}</div>
        <Divider />
        <Row wrap={false}>
          {/* <Col span={(showQrCode && !printing) ? 16 : 24} style={printing ? { flex: '0 0 auto', width: 'calc(100% - 122px)', maxWidth: 'none' } : {}}> */}
          <Col span={(showQrCode && !printing) ? 20 : 24}>
            <Descriptions column={showQrCode ? 3 : 4} className='noBottom'>
              <Descriptions.Item label="订单编号">{detail.order_id}</Descriptions.Item>
              <Descriptions.Item label="创建时间" /* style={{ width: printing ? '40%' : 'auto' }} */>{detail.create_date + ' ' + detail.create_time}</Descriptions.Item>
              {
                (!printing && detail.manager_flag === 'Y' && !isNull(detail.manager_entity.settle_no)) && <Descriptions.Item label="结算单号" className='print_no'>{detail.manager_entity.settle_no}</Descriptions.Item>
              }
              {(!printing && !isNull(detail.settle_no) && detail.manager_flag !== 'Y' && detail.order_status !== 'C' && detail.order_status !== 'E') && <Descriptions.Item label="结算单号" className='print_no'>{detail.settle_no}</Descriptions.Item>}
              {!isNull(detail.pay_time) && <Descriptions.Item label="支付时间">{detail.pay_time}</Descriptions.Item>}
              <Descriptions.Item label="商品原价">{detail.goods_total_price}（元）</Descriptions.Item>
              <Descriptions.Item label="商品数量">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{getGoodsNum(detail.order_goods_list, 'goods_num')}</span>（件）
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">{detail.total_price}（元）{detail.manager_flag === 'Y' && '（通过出院办结合并支付）'}</Descriptions.Item>
              <Descriptions.Item label="订单折扣">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.discount_ratio}</span>
              </Descriptions.Item>
              <Descriptions.Item label="欠款">{parseFloat(detail.owing_price ?? 0).toFixed(2)}（元）</Descriptions.Item>
              <Descriptions.Item label="邮寄费用">{parseFloat(detail.franking ?? 0).toFixed(2)}（元）</Descriptions.Item>
              <Descriptions.Item label="结算价格">
                <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{detail.sett_price}</span>（元）
              </Descriptions.Item>
              <Descriptions.Item label="已开具发票">{detail.is_ballot === 'Y' ? '已开具' : '未开'}</Descriptions.Item>
              <Descriptions.Item label="收件人">{detail.frank_name || '-'}</Descriptions.Item>
              <Descriptions.Item label="收件人电话">{detail.frank_phone || '-'}</Descriptions.Item>
              {(printing && detail.goods_dept_code === '11232300') && <Descriptions.Item label="取货地址">生活服务楼三楼314号房</Descriptions.Item>}
            </Descriptions>
          </Col>
          {
            (showQrCode && !printing) && <Col span={4} style={printing ? { flex: '0 0 auto', width: 122 } : {}}>
              {<Descriptions column={1}>
                <Descriptions.Item label="付款码" className={printing ? 'qrCodeLabel' : ''}>
                  <QRCode
                    // value参数为生成二维码的链接
                    value={detail.pay_qr_code_url || ''}
                    // 二维码的宽高尺寸
                    size={100}
                    // 二维码的颜色
                    fgColor="#000"
                    renderAs="svg"
                  />
                </Descriptions.Item>
              </Descriptions>}
            </Col>
          }
        </Row>
        <Descriptions column={1}>
          <Descriptions.Item span={1} label="收件地址">{detail.frank_address || '-'}</Descriptions.Item>
        </Descriptions>
        <Descriptions column={1}>
          <Descriptions.Item span={1} label="订单备注1" className='print_no'>{detail.remarks || '-'}</Descriptions.Item>
        </Descriptions>
        <Descriptions column={1}>
          <Descriptions.Item span={1} label="订单备注2" className='print_no'>{detail.sec_remarks || '-'}</Descriptions.Item>
        </Descriptions>

        {
          (detail.order_status === 'A' || detail.order_status === 'R') && <React.Fragment>
            <div style={{ marginTop: 10, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.退款信息`}</div>
            <Divider />
            <ProTable
              rowKey="record_id"
              options={false}
              search={false}
              columns={columns2}
              pagination={false}
              dataSource={detail.refund_order_goods_list}
              bordered />

            <Descriptions style={{ marginTop: 10 }} column={4}>
              {!isNull(detail.refund_order_no) && <Descriptions.Item label="退款单号">{detail.refund_order_no}</Descriptions.Item>}
              {!isNull(detail.refund_time) && <Descriptions.Item label="退款时间">{detail.refund_time}</Descriptions.Item>}
              <Descriptions.Item label="退款数量"><span className='red bold'>{getGoodsNum(detail.refund_order_goods_list, 'refund_num')}</span>（件）</Descriptions.Item>
              <Descriptions.Item label="退款总额"><span className='red bold'>{detail.refund_price}</span>（元）</Descriptions.Item>
            </Descriptions>
          </React.Fragment>
        }
        {
          !isNull(detail.approve_list) &&
          <>
            <div style={{ marginTop: 10, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.审批记录`}</div>
            <Divider />
            <ProTable<STOCKGOODSAPI.GoodsItem>
              rowKey="approve_id"
              options={false}
              search={false}
              columns={columns3}
              pagination={false}
              dataSource={detail.approve_list}
              bordered />
          </>
        }

        {
          getSurveyIsShow() &&
          <>
            <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.患者调研`}</div>
            <Divider />
            <Descriptions style={{ marginTop: 10 }} column={4}>
              <Descriptions.Item label="随访调研表">{detail.survey_title}</Descriptions.Item>
              <Descriptions.Item label="随访时间">{detail.survey_date}</Descriptions.Item>
            </Descriptions>
          </>
        }

        <Divider /* className='print_no' */ />
        <Descriptions column={4} /* className='print_no' */>
          <Descriptions.Item label="订单创建人">{detail.create_user_name}</Descriptions.Item>
          <Descriptions.Item label="订单修改人">{detail.modify_user_name || '无'}</Descriptions.Item>
          <Descriptions.Item label="订单责任人">{detail.order_person || '无'}</Descriptions.Item>
          <Descriptions.Item label="订单状态">
            <span style={{ color: '#1F1F1F', fontWeight: 'bold' }}>{OrderStatus[detail.order_status as string]}</span>
          </Descriptions.Item>
        </Descriptions>
      </div>
    </Modal>

    {
      // 审批拒绝输入原因弹窗
      showRejectDialog &&
      <ModalForm
        title='审批拒绝'
        width='500px'
        visible
        layout='horizontal'
        modalProps={{
          onCancel: () => setShowRejectDialog(false),
          maskClosable: false,
        }}
        onFinish={async (values) => {
          reject(values.reason);
        }}
      >
        <ProForm.Group>
          <ProFormText placeholder="请输入审批拒绝原因" name="reason" width="md" />
        </ProForm.Group>
      </ModalForm>
    }
    {
      showCancel &&
      <Modal
        visible
        title='提示'
        maskClosable={false}
        footer={[<Button onClick={() => setShowCancel(false)}>再想想</Button>,
        <Button type='primary' onClick={async () => {
          await managerCancel(detail.manager_order_id).then(res => {
            showMsg('支付已取消', 'success');
            setShowCancel(false);
            optCallback?.({});
            init();
          }).catch(error => {
            showMsg(error?.data?.errmsg)
          });
        }}>取消支付</Button>,
        <Button type='primary' onClick={async () => {
          await managerCancel(detail.manager_order_id).then(async () => {
            await updateOnceOrderStatus({ order_id: detail.order_id, order_status: 'E' }).then(res => {
              showMsg('订单已取消', 'success');
              setShowCancel(false);
              optCallback?.({});
              init();
            }).catch(error => {
              showMsg(error?.data?.errmsg)
            });
          }).catch(error => {
            showMsg(error?.data?.errmsg)
          });
        }}>取消订单</Button>]}
        onCancel={() => {
          setShowCancel(false);
        }}
      >
        <ExclamationCircleOutlined style={{ color: '#faad14' }} /> 该笔订单已经通过出院办结发起结算，是否确认取消？
      </Modal>
    }

    {
      billPrinting && <PrintBillHTML data={detail} after={() => setBillPrinting(false)} />
    }
  </>
}
export default OnceOrderDetail;

export const museText = {
  'H': '远用',
  'S': '近用'
};

// 获得商品数量/退款数量
export const getGoodsNum = (list, key) => {
  let count = 0;
  (list || []).map(item => {
    count += item[key];
  })
  return count;
}

// 格式化验光数据
export const formatData = (value) => {
  return isNull(value) ? '0' : parseFloat(value) >= 0 ? `+${parseFloat(value).toFixed(2)}` : parseFloat(value).toFixed(2)
}

// 判断是否需要显示配镜数据
export const isShowEyeInfo = (data: any) => {
  for (const key of eyeInfoColumn) {
    if (key == 'muse')
      continue;
    if (!isNull(data[key]))
      return true;
  }
  return false;
}

// 判断是否需要显示镜架数据
export const isShowFrameInfo = (data: any) => {
  for (const key of frameInfoColumn) {
    if ((key == 'is_slip' && data[key] != 'Y') || key == 'frame_flag')
      continue;
    if (!isNull(data[key]))
      return true;
  }
  return false;
}
